<?php

namespace Book\Model;

use Think\Model;

class BookReleaseModel extends Model
{

    public function addRelease($book_detail)
    {
        //判断版本
        //添加版本
        $info['bookid']     = $book_detail['id'];
        $info['sha']        = $book_detail['ref'];
        $info['tree']        = $book_detail['tree'];
        $info['repos_name'] = $book_detail['repos_name'];
        $this->add($info);

        //更新book状态
        $update['release_status'] = 1;
        $update['release']        = $book_detail['ref'];
        D('Book')->where(['id' => $book_detail['id']])->save($update);
        return true;
    }

    public function publish($bookid)
    {
        $map['bookid'] = $bookid;
        $map['status'] = 0;
        $detail        = $this->where($map)->find();
        if(empty($detail))
            return true;

        $response_content = D('Book')->gitGetATree($detail['repos_name'], $detail['tree']);
        //分别取内容
        foreach ($response_content['tree'] as $value) {
            $name = $value['path'];
            $content = D('Book')->gitGetABlob($detail['repos_name'], $value['sha']);
            $content = base64_decode($content);
            if($name == 'SUMMARY.md'){
                //获取目录内容
                //格式化内容
                $tree = $this->getTree($content);
            }
            //报错content数组
            $articles[$name] = $content;
        }
        //获取所有目录文件
        $file_list = array_keys($tree);
        array_unshift($file_list, 'SUMMARY.md');
        //判断原本文件是否存在
        $map_exist['bookid'] = $bookid;
        $list_exist = M('book_chapter_release')->where($map_exist)->field('name')->select();
        $add_list = $edit_list = $delete_list = [];
        $list_exist = array_column($list_exist, 'name');
        if(empty($list_exist)){
            $add_list = $file_list;
        }else{
            //不存在的值，添加到add_list
            $add_list = array_filter($file_list, function($var)use($list_exist){
                return !in_array($var, $list_exist);
            });
            $edit_list = array_filter($file_list, function($var)use($list_exist){
                return in_array($var, $list_exist);
            });
            $delete_list = array_filter($list_exist, function($var)use($file_list){
                return !in_array($var, $file_list);
            });
        }
        $this->startTrans();
        //添加
        if(!empty($add_list)){
            foreach ($add_list as $name) {
                $info = [];
                $info['content'] = !empty($articles[$name]) ? $articles[$name] : '';
                $info['name'] = $name;
                $info['bookid'] = $bookid;
                $info['title'] = $tree[$name]['title'] ? $tree[$name]['title'] : '';
                $data_add_list[] = $info;
            }
            M('book_chapter_release')->addAll($data_add_list);
        }
        //修改
        if(!empty($edit_list)){
            foreach ($edit_list as $name) {
                $info = [];
                $info['content'] = !empty($articles[$name]) ? $articles[$name] : '';
                $info['title'] = $tree[$name]['title'] ? $tree[$name]['title'] : '';
                $map_edit['bookid'] = $bookid;
                $map_edit['name'] = $name;
                M('book_chapter_release')->where($map_edit)->save($info);
            }
        }
        //删除
        if(!empty($delete_list)){
            $map_delete['bookid'] = $bookid;
            $map_delete['name'] = ['in', $delete_list];

            M('book_chapter_release')->where($map_delete)->delete();
        }
        //更新SUMMARY.md
        $list = M('book_chapter_release')->where($map_exist)->field('id,name')->index('name')->select();
        foreach ($tree as $name => $info) {
            $pid = $info['parent'] == 0 ? 0 : $list[$info['parent']]['id'];
            $tree[$name]['pid'] = $update_info['pid'] = (int)$pid;
            $tree[$name]['id'] = (int)$list[$name]['id'];
            $tree[$name]['path'] = (string)$list[$name]['id'];
            M('book_chapter_release')->where(['id' => $list[$name]['id']])->save($update_info);
        }
        //更新tree,SUMMARY.md
        $tree_list = listToTree($tree, 'id', 'pid', 'articles');
        M('book_chapter_release')->where(['id' => $list['SUMMARY.md']['id']])->save(['content' => json_encode($tree_list)]);
        //更新状态
        $this->where(['id' => $detail['id']])->save(['status' => 1]);
        M('book')->where(['id' => $detail['bookid']])->save(['release_status' => 0]);
        $this->commit();
    }

    public function getTree($content){
        $list = explode("\n", $content);
        if($list){
            $tree = $summary_list = [];

            //循环，先找出各级的父级，如果没有，则为0
            foreach ($list as $key => $value) {
                $info = [];
                preg_match('/^(\*|\s+\*) \[(.*)\]\((.*)\)/i', $value, $matchs);
                if(!empty($matchs)){
                    $info['title'] = $matchs[2];
                    $info['name'] = $matchs[3];
                    $info['ref'] = $matchs[3];
                    // $info['pre'] = $matchs[1];
                    $info['level'] = (strlen($matchs[1])-1)/4 + 1;
                    /*if($key == 0){
                        $info['parent'] = 0;
                    //如果层级和上一层一样
                    }elseif($info['level'] == ){

                    }
                    var_dump($info);*/
                    if($key == 0 || $info['level'] == 1){
                        $info['parent'] = 0;
                        $summary_list[$key] = $info;
                        $tree[$info['name']] = $info;
                        continue;
                    }else{
                        if($info['level'] == $summary_list[$key - 1]['level']){
                            //level一样， 则pid一样
                            $info['parent'] = $summary_list[$key - 1]['parent'];
                        }elseif($info['level'] > $summary_list[$key - 1]['level']){
                            //level大于上一层， 只能是上一层的子级
                            $info['parent'] = $summary_list[$key - 1]['name'];
                        }else{
                            //level小于上一层 1/ 3
                            $dif_level = $summary_list[$key - 1]['level'] - $info['level'];
                            
                            $current = $summary_list[$key - 1]['name'];
                            //循环， 取出上一层的父级
                            for($level = $summary_list[$key - 1]['level']; $level <= $dif_level; $level --){
                                $current = $tree[$current]['parent'];
                            }
                            $info['parent'] = $current;
                        }
                        $summary_list[$key] = $info;
                        $tree[$info['name']] = $info;
                    }
                }
            }
            var_dump($tree);
            return $tree;
            if(!empty($tree)){
                $return = listToTree($tree, 'name', 'parent', 'articles');
            }
        }
        var_dump($return);
        var_dump($list);
    }

    public function getBookSummary($bookid){
        $map['bookid'] = $bookid;
        $map['name'] = 'SUMMARY.md';

        $content = M('book_chapter_release')->where($map)->getField('content');

        return json_decode($content, true);
    }

    public function getArticleById($bookid, $id){
        $map['bookid'] = $bookid;
        $map['id'] = $id;

        $detail = M('book_chapter_release')->where($map)->find();

        //测试部分
        if(strpos($detail['name'], 'm.wuyouhui.net') !== false && empty($detail['content'])){
            //获取漫画信息
            $url = 'http://'.substr($detail['name'], 0, -3);
            $snoopy = new \Lain\Snoopy;
            $snoopy->rawheaders["Pragma"] = "no-cache";
            
            $snoopy->fetch($url);
            $html_code = $snoopy->results;
            $pic_urls = cutword($html_code, 'qTcms_S_m_murl_e="', '"');
            $real_urls = explode('$qingtiandy$', base64_decode($pic_urls));
            $content = '';
            foreach ($real_urls as $key => $pic) {
                # code...http://www.wuyouhui.net/
                # ![](../../../images/undraw_choice_9385.png)
                $content .= sprintf("![%s](%s)\n\n", $pic,'http://img.pdosgk.com/pic.php?url=http://www.wuyouhui.net'.$pic);
                
            }
            //保存到数据库
            M('book_chapter_release')->where($map)->save(['content' => $content]);
            $detail['content'] = $content;
            
        }elseif(strpos($detail['name'], 'k.xinshubao.net') !== false && empty($detail['content'])){
            //获取漫画信息
            $url = 'https://'.substr($detail['name'], 0, -3);
            $next_url = str_replace('.html', '_2.html', $url);
            // $snoopy = new \Lain\Snoopy;
            // $snoopy->rawheaders["Pragma"] = "no-cache";
            
            // $snoopy->fetch($url);
            // $html_code = $snoopy->results;
            // //转utf8
            // $html_code = iconv('GB2312', 'UTF-8', $html_code);
            // $content = cutword($html_code, '<div id="nr1" class="nr_nr">', '<div');
            // $content = str_replace('&nbsp;', '', $content);
            // $content = str_replace('<br />', "\n", $content);
            // $content = substr($content, 2);
            $content = $this->getXinshubaoContent($url);
            $next_content = $this->getXinshubaoContent($next_url);
            //看是否有分页
            $content = $content.$next_content;

            $content = str_replace('&nbsp;', '', $content);
            $content = str_replace('<br />', "\n", $content);
            //保存到数据库
            M('book_chapter_release')->where($map)->save(['content' => $content]);
            $detail['content'] = $content;
        }

        return $detail;
    }

    public function getXinshubaoContent($url){
        $snoopy = new \Lain\Snoopy;
        $snoopy->rawheaders["Pragma"] = "no-cache";
        
        $snoopy->fetch($url);
        $html_code = $snoopy->results;
        //转utf8
        $html_code = iconv('GB2312', 'UTF-8', $html_code);
        $content = cutword($html_code, '<div id="nr1" class="nr_nr">', '<div');
        $content = substr($content, 2);
        return $content;
    }
}
